package com.itheima.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UploadController {
    @RequestMapping("/upload")
    public String fileUpload(
            @RequestParam("myFile")MultipartFile multipartFile,
            HttpServletRequest request) {
        //获得上传文件的名称
        String fileName = multipartFile.getOriginalFilename();
        //获取"."所在索引
        int index = fileName.lastIndexOf(".");
        //截取后缀名
        String extendName = fileName.substring(index);
        //生成唯一的文件名称
        String uuid = UUID.randomUUID().toString().replace("-","");
        //获得服务器文件上传路径
        String uploadRealPath = request.getSession().getServletContext().getRealPath("/upload");
        File filePath = new File(uploadRealPath);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        System.out.println(uploadRealPath + File.separator + uuid + extendName);
        try {
            //保存到本地文件
            multipartFile.transferTo(new File(uploadRealPath + File.separator + uuid + extendName));
        } catch (IOException e) {
            e.printStackTrace();
            return "upload fail";
        }
        return "upload success";
    }
}
